package com.feihong.yw189.paidan.fragment.paidan;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.adapter.NewListAdapter;
import com.feihong.yw189.paidan.bean.ListOrderInfo;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.PullRecyclerView;

import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.List;


/**
 * 订单页基类(公共方法)
 * 张鹏
 * 2018.3.1
 */
public class NewOrderList extends BaseFragment {
    private EditText ed_search;
    private DispatchActivity mActivity;
    private NewListAdapter dispatchListAdapter;
    private PullRecyclerView mPullRecyclerView;
    public View fragmentView = null;
    private LinearLayout mConnectErrorLayout;
    private TextView mRequeryDataTv;
    private RelativeLayout mNoDataLayout;
    private int dataSize = 0;
    private String search = "";
    private boolean isSearch = false;

    private LinearLayout mSearchLayout;
    public static NewOrderList newInstance(String tabName) {
        NewOrderList rechargeFragment = new NewOrderList();

        return rechargeFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.item_pd_new, container, false);
        return fragmentView;

    }

    @Override
    protected void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (DispatchActivity) getActivity();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        ed_search.setText("");
        bindData();
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        mSearchLayout = fragmentView.findViewById(R.id.ll_type);
        ed_search = fragmentView.findViewById(R.id.ed_search);
        mConnectErrorLayout = fragmentView.findViewById(R.id.connect_net_error_layout);
        mRequeryDataTv = fragmentView.findViewById(R.id.requery_data_tv);
        mNoDataLayout = fragmentView.findViewById(R.id.null_data_layout);
        mPullRecyclerView = fragmentView.findViewById(R.id.pull_recycler_view);
        mPullRecyclerView.setColorSchemeResources(R.color.orange);
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                ed_search.setText("");
                mPullRecyclerView.enableLoadMore(true);
                page = 1;
                dataSize = 0;
                isSearch = false;
                dispatchListAdapter.clear();
                getData("");
            }

            @Override
            public void onLoadMore() {
                ed_search.setText("");
                getData("");
            }
        });
        dispatchListAdapter = new NewListAdapter(mActivity, () -> mPullRecyclerView.autoRefresh());
        mPullRecyclerView.setAdapter(dispatchListAdapter);
        mRequeryDataTv.setOnClickListener(v -> {
            normalDataLayout();
            mPullRecyclerView.autoRefresh();
        });
        // 监听软键盘回车事件
        ed_search.setOnEditorActionListener((v, actionId, event) -> {

            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NONE
                    || actionId == EditorInfo.IME_ACTION_GO
                    || actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || (event != null && KeyEvent.KEYCODE_ENTER
                    == event.getKeyCode() && KeyEvent.ACTION_DOWN
                    == event.getAction())) {
                closeInputMethod(ed_search);
                //处理事件
                search = ed_search.getText().toString().trim();
                dispatchListAdapter.clear();
                mPullRecyclerView.enableLoadMore(false);
                page = 1;
                if(TextUtils.isEmpty(search)){
                    isSearch = false;
                }else {
                    isSearch = true;
                }
                getData(search);
            }
            return true;
        });
    }

    private void closeInputMethod(View view) {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void bindData() {
        mPullRecyclerView.autoRefresh();
    }


    private int page = 1;
    private HashMap<String, String> numMap = new HashMap<>();

    private void getData(String str) {
        App.getApp().getHttpTools().getNewList(page, str, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (fragmentIsOnDestory() || _mActivity == null || _mActivity.isFinishing() || _mActivity.isDestroyed()) {
                    return;
                }
                if (mPullRecyclerView != null) {
                    mPullRecyclerView.postDelayed(() -> {
                        mPullRecyclerView.stopRefresh();
                        mPullRecyclerView.stopLoadMore();
                    }, 300);
                }
                try {
                    Gson gson = new Gson();
                    ListOrderInfo paiDanOrder = gson.fromJson(result, ListOrderInfo.class);
                    if (paiDanOrder == null) {
                        ToastUtils.showShortToast(mActivity, "获取订单失败！请重试");
                        mPullRecyclerView.enableLoadMore(false);
                        if (dataSize == 0) {
                            noDataLayout();
                        } else {
                            normalDataLayout();
                        }
                        return;
                    }

                    if (paiDanOrder.getStatus() == 1) {

                        numMap = new HashMap<>();
                        if (paiDanOrder.getData() == null || paiDanOrder.getData().getData().size() == 0) {
                            mPullRecyclerView.enableLoadMore(false);
                            if (dataSize == 0) {
                                noDataLayout();
                            } else {
                                normalDataLayout();
                            }
                            ToastUtils.showShortToast(mActivity, "暂无更多订单！");

                        } else {
                            List<ListOrderInfo.DataBean.OrderItemBean> data = paiDanOrder.getData().getData();
                            dataSize += data.size();
                            if (data.size() < 10 || isSearch) {
                                mPullRecyclerView.enableLoadMore(false);
                            } else if(!isSearch){
                                page++;
                            }
                            dispatchListAdapter.addAll(data);
                            normalDataLayout();
                        }
                    } else if (paiDanOrder.getStatus() == 401) {
                        Boolean sucRef = RefReshToken.refshToken();
                        if (sucRef) {
                            getData(str);
                        } else {
                            RefReshToken.exitLogin();
                        }
                    } else {
                        if (dataSize == 0) {
                            noDataLayout();
                        } else {
                            normalDataLayout();
                        }
                        ToastUtils.showShortToast(mActivity, paiDanOrder.getInfo());
                    }
                } catch (Exception e) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (fragmentIsOnDestory() || _mActivity == null || _mActivity.isFinishing() || _mActivity.isDestroyed()) {
                    return;
                }
                if (mPullRecyclerView != null) {
                    mPullRecyclerView.postDelayed(() -> {
                        mPullRecyclerView.stopLoadMore();
                        mPullRecyclerView.stopRefresh();
                    }, 300);
                }
                if (dataSize == 0) {
                    connectErrorLayout();
                } else {
                    noDataLayout();
                    showToast(getResources().getString(R.string.connect_sever_error_toast));
                }
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void noDataLayout() {
        if (mNoDataLayout.getVisibility() == View.GONE) {
            mNoDataLayout.setVisibility(View.VISIBLE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mSearchLayout.setVisibility(View.GONE);
        }
    }

    private void connectErrorLayout() {
        if (mConnectErrorLayout.getVisibility() == View.GONE) {
            mNoDataLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.VISIBLE);
            mPullRecyclerView.setVisibility(View.GONE);
            mSearchLayout.setVisibility(View.GONE);
        }
    }

    private void normalDataLayout() {
        if(mSearchLayout.getVisibility() != View.VISIBLE){
            mNoDataLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
            mSearchLayout.setVisibility(View.VISIBLE);
        }
    }
}
